package cloud.server3.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import org.apache.log4j.Logger;

import java.net.InetSocketAddress;
import java.util.Scanner;

/**
 * <b>标题: </b><br />
 * 
 * <pre>
 * </pre>
 *
 * @author 毛宇鹏
 * @date 创建于 上午10:56 2018/4/25
 */
public class NettyClient {

	private static final Logger log = Logger.getLogger(NettyClient.class);

	public Bootstrap b;
	public ChannelFuture f;
	public final EventLoopGroup workerGroup = new NioEventLoopGroup();

	public NettyClient(InetSocketAddress address) {
		try {
			log.info("init...");
			b = new Bootstrap();
			b.group(workerGroup);
			b.channel(NioSocketChannel.class);
			b.handler(new ChannelInitializer<SocketChannel>() {
				@Override
				protected void initChannel(SocketChannel socketChannel) {
					// 解码编码
					socketChannel.pipeline().addLast(new StringDecoder(CharsetUtil.UTF_8));
					socketChannel.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
					 // 自己的逻辑Handler
					socketChannel.pipeline().addLast(new ClientHandler());
				}
			});
			f = b.connect(address).sync();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void start() throws InterruptedException {
		Channel channel = f.channel();
		// 向服务器发送消息
		Scanner scanner = new Scanner(System.in);
		while (true) {
			Thread.sleep(500);
			System.out.println("请输入发送的消息：");
			channel.writeAndFlush(scanner.next());
		}
	}
}